<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>personnel_management</title>
    <link rel="stylesheet" href="../../../static/layer/css/layui.css" media="all"/>
    <link rel="stylesheet" href="../../../static/css/font-awesome.min.css" media="all">
    <style>
        /* 房源下拉框 */
        .choose-room {
            cursor: pointer;
        }

        .room-select-box-container {
            position: absolute;
            padding: 5px 0;
            z-index: 999;
            min-width: 100%;
            border: 1px solid #d2d2d2;
            max-height: 300px;
            overflow-y: auto;
            background-color: #fff;
            border-radius: 2px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, .12);
            box-sizing: border-box;
        }

        .displayflex {
            display: flex;
        }

        .box-container {
            width: 120px;
            height: 200px;
            display: inline-block;
            vertical-align: top;
            list-style: none;
            margin: 0;
            padding: 0;
            border-right: 1px solid #e9e9e9;
            overflow: auto;
        }
        .business-box-container {
            width: 150px;
        }
        .building-box-container {
            width: 195px;
        }
        .box-container dd {
            cursor: pointer;
            padding: 0 10px;
            line-height: 36px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .box-container dd:hover {
            background-color: #f2f2f2;
        }

        .box-container dd.layui-this {
            background-color: #5FB878;
            color: #fff;
        }

        .business-box-container {

        }

        .building-box-container {
            display: none;
        }

        .layui-disabled, .layui-disabled:hover:hover {
            cursor: pointer !important;
        }

    </style>
</head>
<body>
<div style="padding: 20px; position: relative;">
    <div class="operateTable">
        名称：
        <div class="layui-inline">
            <input class="layui-input" name="id" id="filter-id" placeholder="请输入关键字" autocomplete="off">
        </div>
        <button class="layui-btn" data-type="reload">搜索</button>
        <!--<div class="fr authority" style="height: 40px;"> <button class="layui-btn layui-btn-primary layui-btn-radius" style=" height: 31.333334px;">本人权限</button></div>-->
    </div>
    <div class="operateTable" style="position: absolute; top: 20px; right: 20px;">
        <button class="layui-btn addUser" data-type="addUser"><i class="layui-icon"></i> 新建人员</button>
    </div>

    <table class="layui-table" lay-data="{height:'full-110', url:'/user/json/', page:true, limit:20, id:'userTable'}"
           lay-filter="role">
        <thead>
        <tr>
            <th lay-data="{checkbox:true, fixed: true}"></th>
            <th lay-data="{field:'USERNAME', width:150 ,align: 'center'} ">登录名</th>
            <th lay-data="{field:'NAME', width:150 ,align: 'center'}">昵称</th>
            <th lay-data="{field:'ROLE_NAME', width:200 ,align: 'center', templet: '#roleTpl'}">角色</th>
            <th lay-data="{field:'BUILDING_NUM', width:120 ,align: 'center', event: 'setAuth', style:'cursor: pointer;', templet: '#buildingAuthTpl'}">楼宇权限</th>
            <th lay-data="{field:'PHONE', width:130 ,align: 'center'}">联系方式</th>
            <th lay-data="{field:'EMAIL', width:200 ,align: 'center'}">电子邮箱</th>
            <th lay-data="{field:'BZ', width:200 ,align: 'center'}">备注</th>
            <th lay-data="{field:'LAST_LOGIN', width:180 ,align: 'center'}">最后登录时间</th>
            <th lay-data="{fixed: 'right', width:150, align:'center', toolbar: '#barDemo'}">操作</th>
        </tr>
        </thead>
    </table>
    <script type="text/html" id="roleTpl">
        {{# var type = d.USER_TYPE }}
        {{# if (type == '63d5ecdb7af94593866a36eb026daaa6'){ }}
        <span>{{ d.ROLE_NAME }}</span>
        {{# } else{ }}
        <span>系统管理员（主账号）</span>
        {{# } }}
    </script>
    <script type="text/html" id="buildingAuthTpl">
        {{# var type = d.USER_TYPE }}
        {{# if (type == '63d5ecdb7af94593866a36eb026daaa6'){ }}
        <span class="layui-table-link">{{ d.BUILDING_NUM }}</span>
        {{# } else{ }}
        <span>全部</span>
        {{# } }}
    </script>
    <script type="text/html" id="barDemo">
        {{# var type = d.USER_TYPE }}
        {{# if (type == '63d5ecdb7af94593866a36eb026daaa6'){ }}
        <!--<a class="layui-btn layui-btn-primary layui-btn-mini" lay-event="detail">查看</a>-->
        <a class="layui-btn layui-btn-mini" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-mini" lay-event="del">删除</a>
        {{# } else{ }}

        {{# } }}
    </script>
</div>
<script type="text/javascript" src="../../../static/layer/layui.js"></script>
<script type="text/javascript" src="../../../static/js/common/queryUtils.js"></script>
<script>
    var table;
    var chooseIdArray = new Array(); // 选中的ID数组
    layui.use(['jquery', 'table', 'form', 'layer'], function () {
        table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;

        var active = {
            reload: function () {
                var name = $('#filter-id').val();
                table.reload('userTable', {
                    where: {
                        NAME: name
                    }
                });
            },
            addUser: function () {
                layer.open({
                    type: 2,
                    title: '新增人员',
                    shadeClose: false,
                    shade: [0.3],
                    maxmin: true, //开启最大化最小化按钮
                    area: ['900px', '90%'],
                    scrollbar: false, //屏蔽滚动条
                    content: 'operate.html?type=add'
                });
            },
            // 通过用户ID取数据权限
            initDataAuth: function (userId) {
                $.ajax({
                    url: "/shsRole/dataAuth",
                    data: {USER_ID: userId},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {
                            if (!!res.data) {
                                for (var i = 0; i < res.data.length; i++) {
                                    chooseIdArray.push(res.data[i].DATA_ID);
                                }
                            }
                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            },
            // 保存用户数据权限
            saveDataAuth: function (type, userId, dataId, o) {
                $.ajax({
                    url: "/shsRole/saveDataAuth",
                    data: {TYPE: type, USER_ID: userId, DATA_ID: dataId},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {
                            //同步更新表格和缓存对应的值
                            o.update({
                                BUILDING_NUM: chooseIdArray.length
                            });
                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            },
            // 初始化房间下拉框商圈
            initBusiness: function (userId, o) {
                $.ajax({
                    url: "/business/list",
                    data: {},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {
                            $(".business-box-container").empty();
                            if (res.data.length > 0) {
                                for (var i = 0; i < res.data.length; i++) {
                                    if (res.data[i].IS_OPEN === "on") {
                                        var str = '<dd data-id="' + res.data[i].ID + '" title="' + res.data[i].BUSINESS_NAME + '">' + res.data[i].BUSINESS_NAME + '</dd>';
                                        $(".business-box-container").append(str);
                                    }
                                }
                            }
                            $(".business-box-container dd").click(function (e) {
                                $(this).addClass('layui-this').siblings().removeClass("layui-this");
                                active.initBuilding(userId, $(this).data("id"), o);
                                $(".building-box-container").show();
                            });
                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            },
            // 初始化房间下拉框楼宇
            initBuilding: function (userId, businessId, o) {
                $.ajax({
                    url: "/building/list",
                    data: {BUSINESS_ID: businessId, ADMIN_TYPE: 1},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {
                            $(".building-box-container").empty();
                            if (res.data.length > 0) {
                                for (var i = 0; i < res.data.length; i++) {
                                    var chooseFlag = "";
                                    $.each(chooseIdArray, function (index, value) {
                                        if (res.data[i].BUILDING_ID == value) {
                                            chooseFlag = "checked";
                                        }
                                    });
                                    if (res.data[i].IS_OPEN === "on") {
                                        var str = '<dd data-id="' + res.data[i].BUILDING_ID + '" title="' + res.data[i].BUILDING_NAME + '"><input disabled type="checkbox" name="building" value="' + res.data[i].BUILDING_ID + '" lay-filter="building" lay-skin="primary" ' + chooseFlag + '>　' + res.data[i].BUILDING_NAME + '</dd>';
                                        $(".building-box-container").append(str);
                                    }
                                }
                                form.render();
                            }
                            $(".building-box-container dd").click(function (e) {
                                var val = $(this).find("input[type='checkbox']").val();
                                if ($(this).find("input[type='checkbox']").is(":checked")) {
                                    $(this).find("input[type='checkbox']").prop("checked", false);
                                    chooseIdArray = $.grep(chooseIdArray, function (value) {
                                        return value != val;
                                    });
                                    active.saveDataAuth('1', userId, val, o);
                                } else {
                                    $(this).find("input[type='checkbox']").prop("checked", true);
                                    chooseIdArray.push(val);
                                    active.saveDataAuth('0', userId, val, o);
                                }
                                form.render();
                                e.stopPropagation();
                            });
                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            }
        };

        $('.operateTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //监听工具条
        table.on('tool(role)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') {
                layer.open({
                    type: 2,
                    title: data.USERNAME,
                    shadeClose: false,
                    shade: [0.3],
                    maxmin: true, //开启最大化最小化按钮
                    area: ['900px', '90%'],
                    scrollbar: false, //屏蔽滚动条
                    content: 'operate.html?type=view&id=' + data.USER_ID
                });
            } else if (obj.event === 'del') {
                layer.confirm('确认删除 ' + data.USERNAME + ' 吗', {offset: '150px'}, function (index) {
                    layer.close(index);
                    $.ajax({
                        url: "/user/edit",
                        data: {USER_ID: data.USER_ID, IS_DEL: 1},
                        dataType: "json",
                        type: "post",
                        async: false,
                        success: function (res) {
                            if (res.errcode === "0") {
                                reloadTable();
                                layer.msg(data.USERNAME + " 已删除", {offset: '150px'});   // 弹出删除成功
                            } else if (res.errcode === "1") {
                                layer.msg(res.errmsg, function () {
                                });
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.error(XMLHttpRequest.status);
                            console.error(XMLHttpRequest.readyState);
                            console.error(textStatus);
                        }
                    });
                });
            } else if (obj.event === 'edit') {
                layer.open({
                    type: 2,
                    title: "编辑 " + data.USERNAME,
                    shadeClose: false,
                    shade: [0.3],
                    maxmin: true, //开启最大化最小化按钮
                    area: ['900px', '90%'],
                    scrollbar: false, //屏蔽滚动条
                    content: 'operate.html?type=edit&id=' + data.USER_ID
                });
            } else if(obj.event === 'setAuth'){
                var html = (function () {/*
                  <!DOCTYPE html>
                  <html>
                    <body>
                      <div class="layui-form">
                          <div id="room-select-box-container" class="room-select-box-container">
                              <div class="displayflex">
                                  <dl class="box-container business-box-container">
                                  </dl>
                                  <dl class="box-container building-box-container">
                                  </dl>
                              </div>
                          </div>
                      </div>
                    </body>
                  </html>
                */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

                if (obj.data.USER_TYPE == "95bb91515192430bb7a6b5d0a0876542") {
                    return false;
                }

                layer.open({
                    type: 1,
                    title: "编辑 " + data.USERNAME + " 数据权限",
                    shadeClose: false,
                    shade: [0.3],
                    maxmin: false, //开启最大化最小化按钮
                    resize: false, //禁止拉伸
                    area: ['350px', '255px'], //宽高
                    scrollbar: false, //屏蔽滚动条
                    content: html
                });
                chooseIdArray = new Array();
                active.initDataAuth(data.USER_ID);
                active.initBusiness(data.USER_ID, obj);
            }
        })
    });

    function reloadTable() {
        table.reload('userTable', {});
    }
</script>
</body>
</html>